import * as vscode from 'vscode';
import { LLMFactory } from '../../../core/llm/llmFactory';
import { VerticalDiffManager } from '../../../src/diff/vertical/manager';
import { FuzzTestGenerator } from './FuzzTestGenerator';

/**
 * 生成 Fuzz 测试用例的主函数
 * 
 * 流程：
 * 1. 定位当前 cpp 目录并输出路径
 * 2. 查找 BUILD.gn 文件并输出路径
 * 3. 分析 test/fuzztest 目录结构
 * 4. 生成 Fuzz 测试文件结构
 * 5. 使用 LLM 生成 Fuzz 测试代码
 */
export async function generateFuzzTest(
    verticalDiffManager: VerticalDiffManager,
    llmFactory: LLMFactory,
    context: vscode.ExtensionContext
): Promise<void> {
    console.log('[FuzzTest] ===== 开始生成 OpenHarmony Fuzz 测试 =====');
    
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showErrorMessage('请先打开一个 C/C++ 代码文件');
        return;
    }

    const document = editor.document;
    const selection = editor.selection;
    
    // 获取选中的代码或整个文件
    const selectedText = selection.isEmpty 
        ? document.getText() 
        : document.getText(selection);
    
    const fileName = document.fileName.split(/[/\\]/).pop() || 'unknown';
    
    console.log('[FuzzTest] 文件:', fileName);
    console.log('[FuzzTest] 选中代码长度:', selectedText.length);
    console.log('[FuzzTest] 是否选中代码:', !selection.isEmpty);
    
    // 发送消息到 webview，开始五步生成流程
    const isWholeFile = selection.isEmpty;
    const startLine = selection.start.line + 1;
    const endLine = selection.end.line + 1;
    
    // 发送消息到 webview
    vscode.commands.executeCommand('HarmonyPilot.harmonyPilotGUIView.focus');
    
    // 等待一下确保 webview 已经加载
    setTimeout(() => {
        vscode.commands.executeCommand('HarmonyPilot.sendToWebview', {
            messageType: 'selectedCodeForFuzz',
            data: {
                fileName,
                startLine,
                endLine,
                selectedText,
                filePath: document.uri.fsPath,
                isWholeFile
            }
        });
        
        console.log('[FuzzTest] 已发送代码到 webview');
    }, 300);
}

/**
 * 直接生成 Fuzz 测试（不通过 webview）
 * 用于后端直接调用
 */
export async function generateFuzzTestDirect(
    document: vscode.TextDocument,
    sourceCode: string,
    llmFactory: LLMFactory,
    sendMessage: (msg: any) => void
): Promise<void> {
    const generator = new FuzzTestGenerator(llmFactory, sendMessage);
    await generator.executeFullWorkflow(document, sourceCode);
}

